<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="90px">
      <el-form-item label="地区" prop="provinceId">
        <matic-select v-model:value="queryParams.provinceId" :objMap="{ value: 'id', label: 'name' }"
          :url="`area/getSonArea/forManager?parentId=${1}`"></matic-select> </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <page-table :url="url.list" ref="table" :tableForm="queryParams" :columns="columns">
      <template #action="scope">
        <el-tooltip content="修改" placement="top">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
        </el-tooltip>
      </template>
      <template #ruleD="{ row }">
        {{ `${row.ruleStartM}月${row.ruleStartD}日 - ${row.ruleEndM}月${row.ruleEndD}日` }}
      </template>
      <template #ruleH="{ row }">
        {{ `${row.ruleStartH}:${row.ruleStartMin} - ${row.ruleEndH}:${row.ruleEndMin}` }}
      </template>
      <template #status="scope">
        <el-switch v-model="scope.row.status" v-if="scope.row.status != undefined" :active-value="1" :inactive-value="0"
          @change="handleDelete(scope.row, scope.row.status)"></el-switch>
      </template>
    </page-table>

    <!-- 添加或修改价格配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
<!--        <el-form-item label="地区" prop="provinceId">-->
<!--          <matic-select v-model:value="form.provinceId" :objMap="{ value: 'id', label: 'name' }"-->
<!--            :url="`area/getSonArea/forManager?parentId=${1}`"></matic-select>-->
<!--        </el-form-item>-->
        <el-form-item label="政策名称" prop="policyId">
          <matic-select v-model:value="form.policyId" :url="`policy/getAllList/forManager`"
            :objMap="{ value: 'id', label: 'title' }" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="时段类型" prop="bucketType">
          <matic-select v-model:value="form.bucketType" :options="[
            { value: 0, label: '普通时段' }, { value: 1, label: '个别时段（与普通时段重叠时，使用个别时段）' }
          ]" :objMap="{ value: 'value', label: 'label' }" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="行业类型" prop="type">
          <matic-select v-model:value="form.type" :options="[
            { value: 1, label: '峰' }, { value: 2, label: '尖' }, { value: 3, label: '平' }, { value: 4, label: '谷' }, { value: 5, label: '深谷' }
          ]" :objMap="{ value: 'value', label: 'label' }" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="电价倍数" prop="priceMultiple">
          <el-input v-model="form.priceMultiple" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="日期规则" prop="ruleEndD">
          <div class="guize">
            <span>从</span>
            <matic-select v-model:value="form.ruleStartM" :options="arrayFromNumber(12)"
              :objMap="{ value: 'value', label: 'value' }" />
            <span>月</span>
            <matic-select v-model:value="form.ruleStartD" :options="getDaysInMonth(form.ruleStartM)"
              :objMap="{ value: 'value', label: 'value' }" />
            <span>日&nbsp;至</span>
            <matic-select v-model:value="form.ruleEndM" :options="arrayFromNumber(12)"
              :objMap="{ value: 'value', label: 'value' }" />
            <span>月</span>
            <matic-select v-model:value="form.ruleEndD" :options="getDaysInMonth(form.ruleEndM)"
              :objMap="{ value: 'value', label: 'value' }" />
            <span>日</span>
          </div>
        </el-form-item>
        <el-form-item label="时间规则" prop="ruleEndMin">
          <div class="guize">
            <span>从</span>
            <matic-select v-model:value="form.ruleStartH" :options="arrayFromNumber(24, 0)"
              :objMap="{ value: 'value', label: 'value' }" />
            <span>时</span>
            <matic-select v-model:value="form.ruleStartMin" :options="arrayFromNumber(1, 0)"
              :objMap="{ value: 'value', label: 'value' }" />
            <span>分&nbsp;至</span>
            <matic-select v-model:value="form.ruleEndH" :options="arrayFromNumber(24, 0)"
              :objMap="{ value: 'value', label: 'value' }" />
            <span>时</span>
            <matic-select v-model:value="form.ruleEndMin" :options="arrayFromNumber(1, 59)"
              :objMap="{ value: 'value', label: 'value' }" />
            <span>分</span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import request from '@/utils/request'
const router = useRouter();
const { proxy } = getCurrentInstance();

const url = ref({
  list: 'electricityPrice/getPage/forManager',
  fine: 'electricityPrice/getOne/forManager',
  delete: 'electricityPrice/disableOrUse/forManager',
  add: 'electricityPrice/save/forManager',
  edit: 'electricityPrice/save/forManager'
});

const open = ref(false);
const title = ref("");
const openDataScope = ref(false);
const table = ref(null);

const columns = ref([{
  key: 'province',
  title: '地区',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'policy',
  title: '政策',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'typeStr',
  title: '用电类型',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'priceMultiple',
  title: '电价倍数',
  ellipsis: true,
  tooltip: true,
},
  {
  key: 'bucketTypeStr',
  title: '时段类型',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'ruleD',
  title: '日期规则',
  width: 180,
  ellipsis: true,
  tooltip: true,
  slots: {
    customKey: 'ruleD',
  },
},
{
  key: 'ruleH',
  title: '时间规则',
  ellipsis: true,
  tooltip: true,
  slots: {
    customKey: 'ruleH',
  },
},
{
  key: 'createTime',
  title: '创建时间',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'createBy',
  title: '创建人',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'abandonedTime',
  title: '废弃时间',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'abandonedBy',
  title: '废弃人',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'status',
  title: '停用|使用',
  align: 'center',
  width: 150,
  slots: {
    customKey: 'status',
  },
},
// {
//   title: '操作',
//   key: 'action',
//   slots: {
//     customKey: 'action',
//   },
//   align: 'center',
//   fixed: 'right',
//   width: 150
// }
]);

const arrayFromNumber = (number, align = 1) => Array.from({ length: number }, (_, index) => ({ value: index + align }));
const currentYear = new Date().getFullYear();
const getDaysInMonth = (month, year = currentYear) => {
  const lastDay = new Date(year, month, 0).getDate();
  return arrayFromNumber(lastDay);
}

const handleDelete = (row, status) => {
  const id = row.id
  let text = row.status == "1" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + '价格' + '"吗?').then(function () {
    return request.get(url.value.delete, { params: { id } });
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
}

/** 数据范围选项*/
const dataScopeOptions = ref([
  { value: "1", label: "全部数据权限" },
  { value: "2", label: "自定数据权限" },
]);

const ruleEndDValidate = (rule, value, callback) => {
  if (!form.value.ruleStartM) {
    callback(new Error('开始月不能为空！'))
  } else if (!form.value.ruleStartD) {
    callback(new Error('开始日不能为空！'))
  } else if (!form.value.ruleEndM) {
    callback(new Error('结束月不能为空！'))
  } else if (!form.value.ruleEndD) {
    callback(new Error('结束日不能为空！'))
  } else {
    callback()
  }
}

const ruleEndMinValidate = (rule, value, callback) => {
  if (!form.value.ruleStartH && form.value.ruleStartH !== 0) {
    callback(new Error('开始时不能为空！'))
  } else if (!form.value.ruleStartMin && form.value.ruleStartMin !== 0) {
    callback(new Error('开始分不能为空！'))
  } else if (!form.value.ruleEndH && form.value.ruleEndH !== 0) {
    callback(new Error('结束时不能为空！'))
  } else if (!form.value.ruleEndMin && form.value.ruleEndMin !== 0) {
    callback(new Error('结束分不能为空！'))
  } else {
    callback()
  }
}

const data = reactive({
  form: {},
  queryParams: {},
  rules: {
    priceMultiple: [{ required: true, message: "价格倍数为空", trigger: "blur" }],
    policyId: [{ required: true, message: "政策名称不能为空", trigger: "blur" }],
    // provinceId: [{ required: true, message: "地区不能为空", trigger: "blur" }],
    type: [{ required: true, message: "行业类型不能为空", trigger: "blur" }],
    bucketType: [{ required: true, message: "时段类型为空", trigger: "blur" }],
    ruleEndD: [
      { required: true, validator: ruleEndDValidate, trigger: 'blur' }
    ],
    ruleEndMin: [{ required: true, validator: ruleEndMinValidate, trigger: 'blur' }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
function getList() {
  table.value.onload();
}
/** 搜索按钮操作 */
function handleQuery() {
  table.value.init();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    title: '',
    customerId: '',
  };
  proxy.resetForm("roleRef");
}
/** 添加价格 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加价格";
}
/** 修改价格 */
function handleUpdate(row) {
  reset();
  const id = row.id
  request.get(url.value.fine, { params: { id } }).then(response => {
    form.value = response.result;
    open.value = true;
    title.value = "修改价格";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        request.post(url.value.edit, form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        request.post(url.value.add, form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}


</script>
<style scoped>
.guize {
  display: flex;
}

.guize span {
  padding: 0 5px;
}
</style>